package stack.era.presentation.side_screen;

import java.awt.BorderLayout;
import java.util.HashMap;

import javax.swing.JDialog;

import stack.era.constants.ScreenAttributes;
import stack.era.constants.FrameAttributes.SideScreen;
import stack.era.presentation.char_side_screen.PlayerCharacterSideScreen;
import stack.era.presentation.frame.ERAFrame;

public class SideScreenManager {

	private static SideScreenManager instance = null;

	private HashMap<SideScreen, Boolean> areSideScreensDisplayed;
	private HashMap<SideScreen, JDialog> openSideScreenDialogs;
	private HashMap<SideScreen, ERASideScreen> sideScreens;

	private SideScreenManager() {
		areSideScreensDisplayed = new HashMap<SideScreen, Boolean>();
		openSideScreenDialogs = new HashMap<SideScreen, JDialog>();
		sideScreens = new HashMap<SideScreen, ERASideScreen>();

		for (SideScreen ss : SideScreen.values()) {
			areSideScreensDisplayed.put(ss, false);
			this.registerSideScreen(ss);
		}
	}

	public static SideScreenManager getInstance() {
		if (instance == null) {
			instance = new SideScreenManager();
		}
		return instance;
	}

	public void showSideScreen(SideScreen ss) {
		this.areSideScreensDisplayed.put(ss, true);
		this.openSideScreenDialogs.get(ss).setVisible(true);
	}

	public void hideSideScreen(SideScreen ss) {
		this.areSideScreensDisplayed.put(ss, false);
		this.openSideScreenDialogs.get(ss).setVisible(false);
	}

	public void toggleSideScreen(SideScreen ss) {
		if (this.isShown(ss)) {
			this.hideSideScreen(ss);
		} else {
			this.showSideScreen(ss);
		}
	}

	private void registerSideScreen(SideScreen ss) {
		JDialog d = null;
		ERASideScreen screen = null;
		switch (ss) {
		case CHARACTER:
			screen = new PlayerCharacterSideScreen();
			d = this.buildSideScreen(ss, screen);
			break;
		}
		if (d != null && screen != null) {
			areSideScreensDisplayed.put(ss, true);
			openSideScreenDialogs.put(ss, d);
			sideScreens.put(ss, screen);
		}
	}

	public boolean isShown(SideScreen ss) {
		return areSideScreensDisplayed.get(ss);
	}

	public void populateSideScreens() {
		for (SideScreen ss : SideScreen.values()) {
			this.sideScreens.get(ss).populate();
		}
	}

	private JDialog buildSideScreen(SideScreen ss, ERASideScreen panel) {
		JDialog dialog = new JDialog(ERAFrame.getInstance(), ss.getTitle(),
				false);
		dialog.setSize(ss.getDialogSize());
		dialog.setResizable(false);
		dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
		dialog.setLayout(new BorderLayout());
		dialog.add(panel, BorderLayout.CENTER);
		dialog.addWindowListener(new SideScreenClosingControl(ss));
		dialog.setLocation((int) (ScreenAttributes.SCREEN_SIZE.getWidth() / 2)
				- (int) (ss.getDialogSize().getWidth() / 2),
				(int) (ScreenAttributes.SCREEN_SIZE.getHeight() / 2)
						- (int) (ss.getDialogSize().getHeight() / 2));
		return dialog;
	}

}
